import { bomApi, EBomSource, EOrderState, IBomListParams } from '@/api';
import { IPlank } from '@/types';
import { dateFormat } from '@/utils';
import { Form, Modal, Select, Table } from 'antd';
import type { DefaultOptionType } from 'antd/es/select';
import type { ColumnsType } from 'antd/es/table';
import React, { useEffect, useState } from 'react';

const log = console.log.bind(null, '[FetchData]');

const sourceOptions: DefaultOptionType[] = [
  { label: '订单', value: EBomSource.ordered },
  { label: '合批', value: EBomSource.merged },
];

const orderStateOptions: DefaultOptionType[] = [
  { label: '已确定', value: EOrderState.confirmed },
  { label: '已下单', value: EOrderState.ordered },
  { label: '待付款', value: EOrderState.payPending },
  { label: '已付款', value: EOrderState.paid },
  { label: '已拆单', value: EOrderState.splited },
  { label: '已合批', value: EOrderState.merged },
  { label: '已开料', value: EOrderState.openedMaterial },
  { label: '已封边', value: EOrderState.edgeSealed },
  { label: '已排孔', value: EOrderState.holesArranged },
  { label: '已包装', value: EOrderState.packed },
  { label: '已入库', value: EOrderState.warehoused },
  { label: '已发货', value: EOrderState.shipped },
  { label: '待审核', value: EOrderState.reviewPending },
  { label: '待确定', value: EOrderState.confirmPending },
  { label: '待收款', value: EOrderState.payCollectPending },
  { label: '已收款', value: EOrderState.payCollected },
  { label: '待拆单', value: EOrderState.splitOrderPending },
  { label: '已完成', value: EOrderState.completed },
  { label: '已备料', value: EOrderState.materialPrepared },
  { label: '已分拣', value: EOrderState.picked },
  { label: '已创建', value: EOrderState.created },
  { label: '待设计', value: EOrderState.designPending },
  { label: '合批中', value: EOrderState.merging },
  { label: '已排产', value: EOrderState.productionScheduled },
  { label: '已拆单', value: EOrderState.splited },
];

interface DataType {
  id: React.Key;
  name: string;
  date: number;
  data: IPlank[];
}

const columns: ColumnsType<DataType> = [
  {
    title: '编号',
    dataIndex: 'id',
  },
  {
    title: '名称',
    dataIndex: 'name',
  },
  {
    title: '日期',
    dataIndex: 'date',
    render(value, record, index) {
      if (!value) return '-';
      return dateFormat(value);
    },
  },
];

interface Pagination {
  total: number;
  pageNum: number;
  pageSize: number;
}

interface Props {
  onConfirm(data: DataType): void;
}
export const FetchData: React.FC<Props> = (props) => {
  const [isModalVisible, setIsModalVisible] = useState(false);
  const [selected, setSelected] = useState<DataType>();
  const [data, setData] = useState<DataType[]>();
  const [source, setSource] = useState<EBomSource>(EBomSource.ordered);
  const [orderState, setOrderState] = useState<EOrderState>();
  const [pagination, setPagination] = useState<Partial<Pagination>>({
    pageNum: 1,
    pageSize: 10,
  });

  function handlePaginationChange(params: Partial<Pagination>) {
    setPagination({
      ...pagination,
      ...params,
    });
  }

  async function refreshData(params?: Partial<IBomListParams>) {
    // log({ source });
    const res = await fetchData({
      source,
      orderState,
      pageNum: pagination.pageNum,
      pageSize: pagination.pageSize,
      ...params,
    });
    const { data: list } = res;
    setData(list);
    return res;
  }

  useEffect(() => {
    refreshData().then((res) => {
      const { total } = res;
      setPagination({ total });
    });
  }, []);

  const showModal = () => {
    setIsModalVisible(true);
  };

  const handleOk = () => {
    if (!selected) {
      alert('未选择数据');
      return;
    }
    log('onConfirm', { selected });
    props.onConfirm(selected);
    setIsModalVisible(false);
  };

  const handleCancel = () => {
    setIsModalVisible(false);
  };

  return (
    <>
      <button onClick={showModal}>获取数据</button>
      <Modal
        title="获取数据"
        visible={isModalVisible}
        onOk={handleOk}
        onCancel={handleCancel}
      >
        <Form
          initialValues={{ source: EBomSource.ordered }}
          onValuesChange={(_, values) => {
            // log('form change');
            // console.log({ values });
            refreshData({ pageNum: 1, ...values }).then((res) => {
              handlePaginationChange({ pageNum: 1, total: res.total });
            });
          }}
        >
          <Form.Item label="来源" name="source">
            <Select options={sourceOptions} onChange={setSource} />
          </Form.Item>
          {source !== EBomSource.merged && (
            <Form.Item label="状态" name="orderState">
              <Select
                options={orderStateOptions}
                onChange={setOrderState}
                allowClear
              />
            </Form.Item>
          )}
        </Form>
        <Table
          rowKey={'id'}
          rowSelection={{
            type: 'radio',
            onSelect(record) {
              setSelected(record);
            },
          }}
          columns={columns}
          dataSource={data}
          onChange={() => {
            // refreshData();
          }}
          pagination={{
            total: pagination.total,
            current: pagination.pageNum,
            pageSize: pagination.pageSize,
            onChange: (pageNum, pageSize) => {
              handlePaginationChange({ pageNum, pageSize });
              refreshData({ pageNum, pageSize });
            },
          }}
        />
      </Modal>
    </>
  );
};

async function fetchData(params: IBomListParams) {
  log({ params });
  const { source } = params;

  const res =
    source === EBomSource.ordered
      ? await bomApi.list(params)
      : await bomApi.getMergePlankList(params);
  bomApi.getMergePlankList(params);
  const { data: list } = res;
  let { total } = res;
  let data = [...list];
  log({ data });
  return { data, total };
}

export default FetchData;
